package com.example.h5server.config;


import com.example.h5server.interceptor.JwtAuthenticationInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Autowired
    private JwtAuthenticationInterceptor jwtAuthenticationInterceptor;

    @Override   //配置鉴权信息
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(jwtAuthenticationInterceptor)
                .addPathPatterns("/api/**")      //增加鉴权的请求路径
                .excludePathPatterns("/api/loginByPassword")
                .excludePathPatterns("/api/upload/image")
                .excludePathPatterns("/api/upload/pdf")

                .excludePathPatterns("/api/exportEmployeeExcel"); //排除不需要鉴权的请求路径
    }

    @Override  //配置跨域信息
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("http://localhost:5217", "https://www.jyszprd.com")
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                .allowedHeaders("*")
                .allowCredentials(true);
    }


    @Value("${file.upload-image-path:./uploadsImg/}")
    private String imageUploadPath;

    @Value("${file.upload-pdf-path:./uploadsPDF/}")
    private String pdfUploadPath;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 映射图片访问路径
        registry.addResourceHandler("/uploadsImg/**")
                .addResourceLocations("file:" + normalizePath(imageUploadPath));

        // 映射PDF访问路径
        registry.addResourceHandler("/uploadsPDF/**")
                .addResourceLocations("file:" + normalizePath(pdfUploadPath));
    }

    /**
     * 规范化路径格式
     */
    private String normalizePath(String path) {
        if (!path.endsWith("/") && !path.endsWith("\\")) {
            path += "/";
        }
        return path.replace("\\", "/");
    }
}
